<script setup>
	import { computed, nextTick, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'

	import ApiParameterForm from './ApiParameterForm.vue'
	import ApiDataPreview from './ApiDataPreview.vue'

	const store = useApiDatasetStore()
	const loading = ref(false)
	const queryResult = ref([])
	const apiList = ref([])
	const activeTab = ref('params')
	const bodyType = ref('none')

	// 组件引用
	const apiParameterFormRef = ref()
	const apiDataPreviewRef = ref()
	const columnSelectorRef = ref()
	const formatConfigRef = ref()

	// 计算是否显示Body配置（GET请求不显示）
	const showBodyConfig = computed(() => {
		const selectedApi = apiList.value.find((api) => api.apiPath === store.formData.itemConfig.apiPath)
		return selectedApi && selectedApi.method && selectedApi.method.toUpperCase() !== 'GET'
	})

	// 打开表单并初始化数据
	const onOpen = (record) => {
		if (record) {
			store.setFormData(record)
			nextTick(() => {
				loadApiList().then(() => {
					if (store.formData.itemConfig.apiPath) {
						// 执行初始查询
						executeQuery()
					}
				})
			})
		}
	}

	// 执行查询
	const executeQuery = async () => {
		if (!store.formData.itemConfig.apiPath) {
			message.warning('请先选择API接口')
			return
		}

		try {
			loading.value = true

			// 构建预览配置
			const previewConfig = {
				type: store.connectorInfo?.type || 'LOCAL_API',
				config: {
					...store.connectorInfo?.config,
					apiPath: store.formData.itemConfig.apiPath,
					method: 'GET'
				},
				params: store.formData.itemConfig.apiParams || {}
			}

			const res = await dataConnectorApi.previewData(previewConfig)
			queryResult.value = res || []
			store.updateQueryResult(queryResult.value)

			// 自动生成列定义
			if (queryResult.value.length > 0) {
				const columns = Object.keys(queryResult.value[0]).map((key) => ({
					title: key,
					dataIndex: key.toLowerCase(),
					key: key,
					width: 180,
					ellipsis: true
				}))
				store.setColumns(columns)
			}
		} catch (error) {
			console.error('查询失败:', error)
			message.error('查询失败：' + (error.message || '未知错误'))
		} finally {
			loading.value = false
		}
	}

	// 获取API接口列表
	const loadApiList = async () => {
		try {
			if (!store.formData.dataConnectorId) {
				return
			}

			// 先获取连接器信息
			const connectorList = await dataConnectorApi.list({ id: store.formData.dataConnectorId })
			if (connectorList && connectorList.length > 0) {
				const connectorInfo = connectorList[0]
				store.setConnectorInfo(connectorInfo)

				// 检查连接器类型是否支持API接口查询
				const supportedTypes = ['LOCAL_API', 'EXTERNAL_API', 'HTTP']
				if (!supportedTypes.includes(connectorInfo.type)) {
					console.warn(`连接器类型 ${connectorInfo.type} 不支持API接口查询`)
					apiList.value = []
					store.setApiList([])
					return
				}

				// 获取API接口列表
				const res = await dataConnectorApi.apisWithMeta({ id: store.formData.dataConnectorId })
				console.log(res)
				apiList.value = res || []
				store.setApiList(apiList.value)
			}
		} catch (error) {
			console.error('获取API接口列表失败:', error)
			// 如果是连接器类型不支持的错误，清空列表而不显示错误
			if (error.message && error.message.includes('该连接器类型不支持API接口查询')) {
				apiList.value = []
				store.setApiList([])
			}
		}
	}

	// 监听API接口选择变化
	watch(
		() => store.formData.itemConfig.apiPath,
		(newApiPath) => {
			if (newApiPath) {
				// 清空之前的查询结果和列选择
				store.updateQueryResult([])
				store.setSelectedColumns([])
				store.setColumns([])

				// 执行新的查询
				executeQuery()
			}
		}
	)

	// 处理API选择变化
	const handleApiChange = (apiPath) => {
		const selectedApi = apiList.value.find((api) => api.apiPath === apiPath)
		if (selectedApi) {
			store.setApiPath(apiPath)
			// 固定使用GET方法
			store.setApiMethod('GET')
			// 执行查询
			executeQuery()
		}
	}

	// 根据路径获取API信息
	const getApiByPath = (path) => {
		return apiList.value.find((api) => api.apiPath === path)
	}

	// 获取请求方法的颜色
	const getMethodColor = (method) => {
		const colors = {
			GET: 'green',
			POST: 'blue',
			PUT: 'orange',
			DELETE: 'red',
			PATCH: 'purple'
		}
		return colors[method] || 'green'
	}

	// 自定义过滤函数
	const filterOption = (input, option) => {
		if (!input) return true
		const searchText = input.toLowerCase()
		const api = apiList.value.find((api) => api.apiPath === option.value)
		if (!api) return false

		// 搜索API路径、方法和描述
		const apiPath = (api.apiPath || '').toLowerCase()
		const apiMethod = (api.method || '').toLowerCase()
		const apiDescription = (api.apiDescription || '').toLowerCase()

		return apiPath.includes(searchText) || apiMethod.includes(searchText) || apiDescription.includes(searchText)
	}

	// 获取数据集配置
	const getConfig = () => {
		if (!store.formData.itemConfig.apiPath) {
			return null
		}
		return {
			apiPath: store.formData.itemConfig.apiPath,
			apiMethod: 'GET', // 固定使用GET方法
			apiParams: store.formData.itemConfig.apiParams,
			selectedColumns: store.formData.itemConfig.selectedColumns,
			formatConfig: store.formData.itemConfig.formatConfig
		}
	}

	defineExpose({
		onOpen,
		getConfig
	})
</script>

<template>
	<div class="api-dataset-config">
		<!-- 顶部请求配置区域 -->
		<div class="request-config-header">
			<div class="request-line">
				<div class="url-selector">
					<a-select
						:filter-option="filterOption"
						:loading="!apiList.length"
						:value="store.formData.itemConfig.apiPath"
						placeholder="请选择API接口"
						class="w-full"
						show-search
						size="large"
						@change="handleApiChange"
					>
						<template #option="{ value }">
							<div class="api-option">
								<div class="option-content">
									<div class="option-header">
										<a-tag :color="getMethodColor(getApiByPath(value)?.method)" size="small">
											{{ getApiByPath(value)?.method || 'GET' }}
										</a-tag>
										<span class="api-path">{{ value }}</span>
									</div>
									<div v-if="getApiByPath(value)?.apiDescription" class="option-summary">
										{{ getApiByPath(value).apiDescription }}
									</div>
									<div
										v-if="getApiByPath(value)?.paramCount && getApiByPath(value).paramCount !== '0'"
										class="option-params"
									>
										需要参数: {{ getApiByPath(value).paramCount }} 个
									</div>
								</div>
							</div>
						</template>
						<a-select-option
							v-for="api in apiList"
							:key="api.apiPath"
							:value="api.apiPath"
							:label="`${api.method} ${api.apiPath}`"
						>
							<a-tag :color="getMethodColor(api.method)" size="small">
								{{ api.method || 'GET' }}
							</a-tag>
							{{ api.apiPath }}
							<span v-if="api.apiDescription" class="ml-2 text-gray-500 text-xs"> - {{ api.apiDescription }} </span>
						</a-select-option>
					</a-select>
				</div>
				<div class="send-button">
					<a-button
						:disabled="!store.formData.itemConfig.apiPath"
						:loading="loading"
						type="primary"
						size="large"
						@click="executeQuery"
					>
						发送
					</a-button>
				</div>
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="config-content">
			<!-- 左侧配置面板 -->
			<div class="config-panel">
				<div class="panel-tabs">
					<a-tabs v-model:activeKey="activeTab" type="line" size="small">
						<a-tab-pane key="params" tab="Params" />
						<a-tab-pane v-if="showBodyConfig" key="body" tab="Body" />
						<a-tab-pane key="preview" tab="数据预览" />
					</a-tabs>
				</div>

				<div class="panel-content">
					<!-- Params 参数配置 -->
					<div v-show="activeTab === 'params'" class="tab-content">
						<api-parameter-form ref="apiParameterFormRef" @change="executeQuery" />
					</div>

					<!-- Body 请求体配置 -->
					<div v-show="activeTab === 'body'" class="tab-content">
						<div class="body-config">
							<div class="body-type-selector">
								<a-radio-group v-model:value="bodyType" size="small">
									<a-radio-button value="none">none</a-radio-button>
									<a-radio-button value="form-data">form-data</a-radio-button>
									<a-radio-button value="x-www-form-urlencoded">x-www-form-urlencoded</a-radio-button>
									<a-radio-button value="raw">raw</a-radio-button>
									<a-radio-button value="binary">binary</a-radio-button>
								</a-radio-group>
							</div>
							<div class="body-content">
								<a-textarea v-if="bodyType === 'raw'" :rows="10" placeholder="请输入请求体内容" />
								<div v-else-if="bodyType === 'form-data'" class="form-data-table">
									<!-- 表格形式的form-data配置 -->
									<div class="table-header">
										<div class="col-checkbox"></div>
										<div class="col-key">KEY</div>
										<div class="col-value">VALUE</div>
										<div class="col-description">DESCRIPTION</div>
										<div class="col-actions"></div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- 数据预览 -->
					<div v-show="activeTab === 'preview'" class="tab-content">
						<div class="preview-container">
							<!-- 数据预览区域 -->
							<div class="data-preview-section">
								<api-data-preview
									ref="apiDataPreviewRef"
									:columns="store.formData.itemConfig.columns"
									:data="queryResult"
									:loading="loading"
									:selected-columns="store.formData.itemConfig.selectedColumns"
								/>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.api-dataset-config {
		display: flex;
		flex-direction: column;
		height: 100%;
		background: #fff;
	}

	.request-config-header {
		padding: 16px 20px;
		border-bottom: 1px solid #f0f0f0;
		background: #fafafa;
	}

	.request-line {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.method-display {
		width: 80px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.url-selector {
		flex: 1;
	}

	.send-button {
		width: 80px;
	}

	.config-content {
		display: flex;
		flex: 1;
		overflow: hidden;
	}

	.config-panel {
		width: 100%;
		background: #fff;
		display: flex;
		flex-direction: column;
	}

	.panel-tabs {
		border-bottom: 1px solid #f0f0f0;
		background: #fff;
		padding: 0 20px;
	}

	.panel-tabs :deep(.ant-tabs-nav) {
		margin-bottom: 0;
	}

	.panel-tabs :deep(.ant-tabs-tab) {
		padding: 12px 16px;
		margin-right: 24px;
	}

	.panel-tabs :deep(.ant-tabs-content-holder) {
		display: none;
	}

	.panel-content {
		flex: 1;
		overflow-y: auto;
	}

	.tab-content {
		padding: 20px;
		min-height: 400px;
	}

	/* API选项样式 */
	.api-option {
		padding: 8px 0;
	}

	.option-content {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.option-header {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.api-path {
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-size: 13px;
		color: #262626;
	}

	.option-summary {
		font-size: 12px;
		color: #8c8c8c;
		margin-left: 24px;
	}

	.option-params {
		font-size: 11px;
		color: #1890ff;
		margin-left: 24px;
		font-weight: 500;
	}

	/* 预览容器样式 */
	.preview-container {
		display: flex;
		flex-direction: column;
		gap: 20px;
		height: 100%;
	}

	.field-config-section {
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		padding: 16px;
		background: #fafafa;
	}

	.format-config-section {
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		padding: 16px;
		background: #fafafa;
	}

	.data-preview-section {
		flex: 1;
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		overflow: hidden;
	}

	/* Body配置样式 */
	.body-config {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.body-type-selector {
		padding-bottom: 16px;
		border-bottom: 1px solid #f0f0f0;
	}

	.body-content {
		flex: 1;
	}

	.form-data-table,
	.header-table {
		border: 1px solid #f0f0f0;
		border-radius: 6px;
	}

	.table-header {
		display: grid;
		grid-template-columns: 40px 1fr 1fr 1fr 40px;
		gap: 8px;
		padding: 12px;
		background: #fafafa;
		border-bottom: 1px solid #f0f0f0;
		font-weight: 600;
		font-size: 12px;
		color: #8c8c8c;
	}

	.col-checkbox {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.col-key,
	.col-value,
	.col-description {
		display: flex;
		align-items: center;
	}

	.col-actions {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* Cookie配置样式 */
	.cookie-config,
	.auth-config {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.empty-state {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200px;
		color: #8c8c8c;
		font-size: 14px;
	}

	.auth-type-selector {
		padding-bottom: 16px;
		border-bottom: 1px solid #f0f0f0;
	}

	.ant-tag {
		margin: 0;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.request-line {
			flex-direction: column;
			gap: 12px;
		}

		.method-display,
		.send-button {
			width: 100%;
		}

		.panel-tabs {
			padding: 0 12px;
		}

		.tab-content {
			padding: 12px;
		}

		.table-header {
			grid-template-columns: 30px 1fr 1fr 30px;
			gap: 4px;
			padding: 8px;
		}

		.col-description {
			display: none;
		}

		.preview-container {
			gap: 12px;
		}

		.field-config-section,
		.format-config-section {
			padding: 12px;
		}
	}
</style>
